<template>
  <div
    class="bg-f8f9fb size-full overflow-auto pb-50 absolute min-h-750 left-0 top-0 flex flex-col justify-between"
  >
    <div class="pt-15 pl-120 mp-ph0 mp-pb0 mp-textAlign-c mp-mb20">
      <a href="http://www.ckjr001.com" target="blank">
        <img src="@/assets/logo/logo-icon.png" class="w-140" alt="" srcset="" />
      </a>
    </div>
    <div
      class="bg-white w-600 margin-0auto shadow-[0_3px_10px_0_rgba(0,0,0,0.1)] rounded-10 py-40 mp-w100"
    >
      <div class="w-3/5 margin-0auto mp-w80">
        <div class="text-center text-16 text-333333 font-bold mb-30">
          {{ $t("login.resetPassword") }}
        </div>
        <template v-if="successStatus === -1">
          <el-form
            ref="modifyPasswordFormRef"
            class="loginForm"
            autoComplete="on"
            :model="modifyPasswordForm"
            :rules="modifyPasswordRules"
            label-position="left"
          >
            <el-form-item>
              <el-input
                v-model="username"
                disabled
                size="large"
                autoComplete="off"
                placeholder="请输入手机号码"
              />
            </el-form-item>
            <el-form-item class="relative" prop="captcha">
              <el-input
                v-model="modifyPasswordForm.captcha"
                size="large"
                name="captcha"
                type="text"
                maxlength="14"
                placeholder="请输入验证码"
              />
              <img
                v-show="captchaImg"
                :src="captchaImg"
                title="点击图片重新获取验证码"
                class="absolute w-120 h-32 bottom-3 right-15 text-center cursor-pointer"
                @click="loadCaptcha"
              />
            </el-form-item>
            <el-form-item class="relative" prop="code">
              <el-input
                v-model="modifyPasswordForm.code"
                autocomplete="off"
                size="large"
                name="code"
                type="text"
                maxlength="16"
                placeholder="请输入验证码"
              />
              <el-button
                :disabled="isClick || modifyPasswordForm.captcha.length < 4"
                class="cursor-pointer absolute w-100 h-20 bottom-4 right-15 text-center"
                text
                @click="getYzcode"
              >
                {{ yzText }}
              </el-button>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-if="newPwdInvisible"
                v-model="modifyPasswordForm.password"
                type="text"
                placeholder="请输入密码"
                clearable
                size="large"
              >
                <template #suffix>
                  <el-icon
                    class="text-16 text-889aa4 cursor-pointer select-none"
                    @click="clickShow"
                  >
                    <View />
                  </el-icon>
                </template>
              </el-input>
              <NewPasswordInput
                v-show="!newPwdInvisible"
                ref="newPwdInvisibleRef"
                :autofocus="false"
                placeholder="请输入密码"
                @clickShow="clickShow"
                @changeValue="getOptionPassword($event, 'password')"
              />
            </el-form-item>
            <el-form-item prop="confirmPwd">
              <el-input
                v-if="confirmPwdInvisible"
                v-model="modifyPasswordForm.confirmPwd"
                type="text"
                size="large"
                placeholder="请输入密码"
                clearable
              >
                <template #suffix>
                  <el-icon
                    class="text-16 text-889aa4 cursor-pointer select-none"
                    @click="clickConfirmPwdShow"
                  >
                    <View />
                  </el-icon>
                </template>
              </el-input>
              <NewPasswordInput
                v-show="!confirmPwdInvisible"
                ref="confirmPwdInvisibleRef"
                :autofocus="false"
                placeholder="请输入确认密码"
                @changeValue="getOptionPassword($event, 'confirmPwd')"
                @clickShow="clickConfirmPwdShow"
              />
            </el-form-item>
          </el-form>
          <div class="pt-8">
            <el-button
              v-loading.fullscreen.lock="fullscreenLoading"
              class="w-full shadow-[0_5px_15px_0_rgba(64,158,255,0.2)]"
              size="large"
              :class="{
                active:
                  modifyPasswordForm.password &&
                  modifyPasswordForm.code &&
                  modifyPasswordForm.confirmPwd,
              }"
              type="primary"
              @click.native.prevent="modifyPassword"
            >
              {{ $t("login.confirmReset") }}
            </el-button>
          </div>
        </template>
      </div>
    </div>
    <div class="text-center text-999999 text-14">
      <div class="pb-23">{{ $t("systemDesc") }}</div>
      <div>{{ $t("systemCopyright") }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormInstance, FormRules } from "element-plus";
import { useUserStore, useUserStoreHook } from "@/store";
import AuthAPI, { resetPasswordFormData } from "@/api/auth";
import NewPasswordInput from "@/views/templatePage/NewPasswordInput/index.vue";
import router from "@/router";

// 密码修改成功状态 -1没成功 1 成功
const successStatus = ref<number>(-1);
// 表单Ref
const modifyPasswordFormRef = ref<FormInstance>();
// 表单数据
const modifyPasswordForm = ref<resetPasswordFormData>({
  password: "",
  confirmPwd: "",
  code: "",
  captcha: "",
  captchaKey: "",
});
// 表单规则
const modifyPasswordRules = ref<FormRules<resetPasswordFormData>>({
  password: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.trim() == "") {
          callback(new Error("请输入密码"));
        } else {
          if (!/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[#@!~%^&*.])[a-zA-Z\d#@!~%^&*.]{6,}$/.test(value)) {
            callback(new Error("请输入至少6位的数字、字母和特殊字符(#@!~%^&*)的组合密码"));
          }
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPwd: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.trim() == "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== modifyPasswordForm.value.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入验证码"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  captcha: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入验证码"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});
// 用户状态管理器
const userStore = useUserStore();
// 获取登录信息
const loginResult = userStore.loginResult;
// 获取用户名用户名
const username = ref<string>(loginResult.username);
// 图片验证码
const captchaImg = ref<string>("");
// 防止多次点击
const isClick = ref<boolean>(false);
// 倒计时定时器
const interval = ref<NodeJS.Timeout | null>(null);
// 验证码倒计时
const yzText = ref<string>("获取验证码");
// 是否开启验证码
const isYz = ref<boolean>(false);
// 是否显示密码
const newPwdInvisible = ref<boolean>(false);
// 是否显示再次确认密码
const confirmPwdInvisible = ref<boolean>(false);
// 倒计时时间
const num = ref<number>(30);
// 获取子组件实例
const newPwdInvisibleRef = ref<InstanceType<typeof NewPasswordInput>>();
const confirmPwdInvisibleRef = ref<InstanceType<typeof NewPasswordInput>>();
// 防止多次点击
const fullscreenLoading = ref<boolean>(false);
// 重新获取验证码
const loadCaptcha = () => {
  AuthAPI.getCaptcha().then((data) => {
    captchaImg.value = data.img;
    modifyPasswordForm.value.captchaKey = data.key;
  });
};
// 验证码倒计时
const getYzMethod = () => {
  isClick.value = true;
  isYz.value = false;
  num.value -= 1;
  yzText.value = num.value + "秒后重新获取";
  if (num.value === 0) {
    clearInterval(interval.value!);
    yzText.value = "获取验证码";
    num.value = 30;
    isClick.value = false;
    isYz.value = true;
  }
};
// 发送短信验证码
const getYzcode = () => {
  clearInterval(interval.value!);
  if (isClick.value) return;
  isClick.value = true;
  yzText.value = "正在发送短信";
  AuthAPI.sendCodeByForget(modifyPasswordForm.value)
    .then(() => {
      getYzMethod();
      interval.value = setInterval(getYzMethod, 1000);
      ElMessage.success("验证码发送成功");
    })
    .catch(() => {
      isClick.value = false;
      yzText.value = "获取验证码";
      loadCaptcha();
    });
};
// 切换密码显示不显示（明文）
const clickShow = () => {
  newPwdInvisible.value = !newPwdInvisible.value;
  newPwdInvisibleRef.value?.replacePwd(modifyPasswordForm.value.password);
};
// 切换密码显示不显示（明文）
const clickConfirmPwdShow = () => {
  confirmPwdInvisible.value = !confirmPwdInvisible.value;
  confirmPwdInvisibleRef.value?.replacePwd(modifyPasswordForm.value.confirmPwd);
};
// 切换密码显示不显示（明文）
const getOptionPassword = (value: string, type: string) => {
  if (type == "password") {
    modifyPasswordForm.value.password = value;
  } else {
    modifyPasswordForm.value.confirmPwd = value;
  }
};
// 修改密码
const modifyPassword = () => {
  // 验证表单参数是否正确
  modifyPasswordFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (fullscreenLoading.value) return;
      fullscreenLoading.value = true;
      AuthAPI.resetPassword(modifyPasswordForm.value)
        .then(async (res) => {
          fullscreenLoading.value = false;
          useUserStoreHook()
            .logout()
            .then(() => {
              location.reload();
              router.push("/login");
            });
        })
        .catch(() => {
          loadCaptcha();
          fullscreenLoading.value = false;
        })
        .finally(() => {
          fullscreenLoading.value = false;
        });
    } else {
      loadCaptcha();
      fullscreenLoading.value = false;
    }
  });
};

onMounted(() => {
  loadCaptcha();
});
</script>
<style scoped lang="scss"></style>
